package com.squirrels.server.service;

import com.squirrels.server.message.Login;
import com.squirrels.server.message.UserData;
import dev.morphia.Datastore;
import dev.morphia.query.MorphiaCursor;
import dev.morphia.query.Query;
import dev.morphia.query.filters.Filters;

import java.util.UUID;

/**
 * 创建者: FlyingSquirrels
 * 创建时间: 2024/8/16 14:47
 * 描述: 用户数据服务
 */
public class UserDataService {

    private static UserDataService userDataService;
    private static Datastore datastore;


    public static synchronized UserDataService operation(Datastore datastore){
        if (null == UserDataService.userDataService) {
            UserDataService.userDataService = new UserDataService();
            UserDataService.datastore = datastore;
        }
        return UserDataService.userDataService;
    }

    // 创建用户数据
    public boolean createUserData(String userId,String nickName,String headImg,String signature){
        // 存在用户
        Query<Login> loginQuery = datastore.find(Login.class);
        MorphiaCursor<Login> loginIter = loginQuery.filter(Filters.eq("_id", userId)).iterator();
        if(false == loginIter.hasNext()){
            return false;
        }
        // 存在数据创建失败
        UserData userExists = getUserDataById(userId);
        if(userExists != null){
            return false;
        }
        // 创建数据
        UserData userData = new UserData();
        userData.setUid(System.currentTimeMillis());
        userData.setUserId(userId);
        userData.setNickName(nickName);
        userData.setHeadImg(headImg);
        userData.setSignature(signature);
        datastore.insert(userData);
        return true;
    }

    // 根据id 查询用户数据
    public UserData getUserDataById(String userId){
        Query<UserData> userQuery = datastore.find(UserData.class);
        MorphiaCursor<UserData> userIter = userQuery.filter(Filters.eq("userId", userId)).iterator();
        boolean isExists = userIter.hasNext();
        if (isExists == false){
            return null;
        }
        return userIter.next();
    }
}
